package com.lagou.sale.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lagou.sale.dao.JedisDao;
import com.lagou.sale.pojo.CreateOrderResult;
import com.lagou.sale.pojo.Order;
import com.lagou.sale.util.GenerateIdUtil;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BuyService {

    @Autowired
    private JedisDao jedisDao;
    @Autowired
    DefaultMQProducer producer;
    ObjectMapper objectMapper = new ObjectMapper();

    public CreateOrderResult createOrder(int num) {
        if (jedisDao.reduceStock(num)) {
            long id = GenerateIdUtil.getNextId();
            try {
                pushOrderToMq(num, id);
                return CreateOrderResult.createSuccessResult(id);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("item: "+num+" sold out");
        }
        return CreateOrderResult.createFailResult();

    }

    private void pushOrderToMq(int itemNum, long orderId) throws InterruptedException, RemotingException, MQClientException, MQBrokerException, JsonProcessingException {
        // 创建order
        Order order = new Order();
        order.setItemNum(itemNum);
        order.setOrderId(orderId);
        byte[] bytes = objectMapper.writeValueAsBytes(order);

        // 发送
        Message message = new Message("createOrder", bytes);
        producer.send(message);
        System.out.println("send order: " + orderId + " to mq");
    }
}
